//var $j = jQuery.noConflict(); //自定义一个比较短快捷方式 
var globalData = {
	//常量参数
	constParam: {
		//url地址参数
		url: {			
			baseUrl: 'http://139.196.167.79:8080',
			baseRequestAdd:'http://139.196.167.79:8080/api/Base/Index',
//			baseUrl: 'http://120.25.212.63:8080',
//			baseRequestAdd: 'http://120.25.212.63:8080/api/Base/Index',
			//主页 
			index_GetSubModels: '/api/Models/GetSubModels', //获取模块列表
			index_GetPageIndexForApp: '/api/PCFunc/GetPageIndexForApp', //证劵信息
			index_GetPageIndexForApp: '/api/PCFunc/GetPageForumsForApp', //获取论坛社区信息
			index_GetHomeBanner: "/api/Banner/GetBannerList", //首页广告
		},
		//常量
		param: {
			TEMPTOKEN: "tempToken", //临时token
			UTOKEN: "uToken", //用户token
			requestData: function(httpMethod, url) {
				var tempToken = globalData.getStorage(globalData.constParam.param.TEMPTOKEN);
				var utoken = globalData.getStorage(globalData.constParam.param.UTOKEN);
				return {
					Token: utoken == null ? tempToken : utoken.AccessToken, //临时口令
					Url: globalData.constParam.url.baseUrl + url, //请求的地址，如："api/Question/SaveQuestionTags"
					HttpMethod: httpMethod, //0=get,1=post
					Device: 4, //设备类型：1=manage,2=iphone,3=android,4=pc
					//RequestParas: data //请求参数,是一个JSON对象的字符串,如："{ID:1}"
				}
			}
		}
	},
	ajaxPost: function(url, data, scall, fcall, isasync, head) {
		if (!data) {
            data = {};
        }       
		var tempd = this.constParam.param.requestData(1, url);
		tempd.RequestParas = JSON.stringify(data); 
		if (typeof tempd !== 'string') {
            tempd = JSON.stringify(tempd);
        }
//		console.log("请求参数："+tempd);
		this.ajax(this.constParam.url.baseRequestAdd,tempd, scall, fcall, isasync, head)
	},
	ajax: function(url, data, scall, fcall, isasync, head) {
		isasync == null ? true : false;
		var type = data.HttpMethod == null || data.HttpMethod == 1 ? "POST" : "GET";
		$.ajax({
			url: url,
			data: data,
			type: type,
			async: isasync,
			dataType: 'json',
			contentType: "application/json",
			success: function(data) {
				if(data.StatusCode == "110"){
					$("#login").modal();
				}					
				else if(data.StatusCode == "120") {  //用户条例
//					globalData.utils.alert(data.msg, function() {						
//						globalData.ajaxPost("/api/LegalDeclaration/AgreeLegalDeclaration", {}, function(r120) {});
//					});
					globalData.utils.setUrl('./html/legal.html',{type:120})
				}
				if(scall)
					scall(data);
			},
			error: function(data) {
				if(fcall)
					scall(data);
			}
		});
	},
	//获取临时token
	getTempToken: function(scall) {
		var self = this;
		if(globalData.getStorage(self.constParam.param.TEMPTOKEN)){
			if(scall){
				scall()
			}
			return;
		}		
		var burl = this.constParam.url.baseUrl;
		var url = "/api/home/GetAccessToken";
		var data = {
			"Url": burl+"/api/home/GetAccessToken",
			"ClientId": "62ccad6d-9611-41c5-96f6-08ec0ada0f68",
			"ClientSecret": "5678"
		};
		this.ajaxPost(url, data, function(res) {
			self.setStorage(self.constParam.param.TEMPTOKEN, res.data.access_token);
			if(scall){
				scall()
			}	
		}, null, false);
	},
	//保存到本地数据
	setStorage: function(k, v) {
		if(typeof(v) == "object")
			v = JSON.stringify(v);
		window.sessionStorage[k] = v;

	},
	//获取本地数据
	getStorage: function(k) {
		var v = window.sessionStorage[k];
		if(/^[{|[].+[}|\]]$/.test(v))
			v = JSON.parse(v);
		return v;
	},
	//删除本地数据
	removeStorage: function(k) {
		return window.sessionStorage.removeItem(k);
	},
	userInfo:{}, //用户信息
	//获取用户信息 
	getUserInfo: function() {
		var userInfo = this.getStorage(this.constParam.param.UTOKEN);
		if(userInfo == null)
			userInfo = {
				isLogin: 0
			};
		else {
			userInfo.isLogin = 1;
		}
		return userInfo;
	},
	userIsLogin:function(cthat,isModal) {
		var user = this.getUserInfo();
		if(user.isLogin == 0) {
			if(isModal){
				$("#login").modal();
			}
			return false;
		}
		return true;
	},
	getTips:function(configKey,modelId,callback){
		var data = {
			'ModelID':modelId,
			'ConfigKey':configKey
		}
		globalData.ajaxPost("/api/AppFun/GetTips", data, function(res) {
			if(callback) callback(res);
		})		
	},
	//工具类
	utils: {
		//格式化时间
		formatTime: function(str) {
			if(str == null || str == "")
				return "";
			var date = new Date(str);
			var year = date.getFullYear();
			var month = date.getMonth() + 1;
			var day = date.getDate();

			var hour = date.getHours();
			var minute = date.getMinutes();
			var second = date.getSeconds();

			return [year, month, day].map(this.formatNumber).join('/') + ' ' + [hour, minute, second].map(this.formatNumber).join(':');
		},
		formatNumber: function(n) {
			n = n.toString();
			return n[1] ? n : '0' + n;
		},
		//弹出框
		alert: function(c, scall) {
			$('#alert').one('click', function() {
				if(scall)
					scall();
			})
			var o = $("#alert p");
			if(c != null) {
				o.html(c);
				$("#alert").modal();
			}
		},
		confirm: function(c, scall) {
			$('#confirm .confirm').one('click', function() {
				if(scall)
					scall();
			})
			var o = $("#confirm p");
			if(c != null) {
				o.html(c);
				$("#confirm").modal();
			}
		},
		//计算分页
		page: function(that, curPage, totalCount) {
			that.page.pageIndex = curPage;
			if(totalCount % that.page.pageSize == 0)
				that.page.pageTotal = totalCount / that.page.pageSize;
			else
				that.page.pageTotal = parseInt(totalCount / that.page.pageSize) + 1;
		},
		//跳转url
		setUrl: function(url, obj,isNew) {
			if(obj)
				url = url + "?request=" + encodeURI(JSON.stringify(obj));
				if(!isNew){
					window.location.href = url;
				}else{
					window.open(url);
				}
				
		},
		//得到url参数
		getUrl: function() {
			var url = location.search
			if(url.length > 9) {
				var obj = decodeURI(url.substring(9, url.length))
				return JSON.parse(obj);
			} else
				return null;
		},
		//获取目标元素
		get_target_dom: function(dom, targetClass) {
			while(!dom.hasClass(targetClass)) {
				dom = dom.parent()
//				console.log(dom)
			}
			return dom;
		},
		//拼接图片前缀
		imagePrefix: function(image,defaultImage,num) {
			if(image != null){
				if(!num){
					return globalData.constParam.url.baseUrl + "/" + image;
				}else{
					return globalData.constParam.url.baseUrl_2 + "/" + image;
				}
			}
				
		},
		//空值 默认值
		notNullDefaulst: function(v, defValue) {
			if(v == null || v == '' || v == 'null')
				v == defValue;
			return v;
		},
		//图片加载事件
		img_onload:function(ev,rate){
			var dom = ev.target			
			var ww =dom.width
			var hh = dom.height
//			console.log(ww,hh)
			var p = rate || 1
//			var p_w = $(dom).parent().width()
//			var p_h = $(dom).parent().height()
			if(ww / hh > p) {
				$(dom).css({
					'height': '100%',
					'width':'auto'
				})
			} else {
				$(dom).css({
					'height': 'auto',
					'width': '100%'
				})
		
			}
		},
		//图片加载错误事件
		imgLoadErr:function(ev){
//			console.log(ev.target)
			ev.target.src = 'imgs/icon.jpg'
		},
		//滚动到顶部
		scrool_top:function(){			
			$('body').scrollTop(0)
		}
	},
	question:{
		go_product_detail:function(item){
			
		}
	}
}
globalData.userInfo = globalData.getUserInfo()
$(window).load(function() {
	$('#ascrail2000>div').css({
		'background-color': '#ff9e2b'
	})
})
window.addEventListener('scroll', function() {
	$('#ascrail2000>div').css({
		'background-color': '#ff9e2b'
	})
})
//流量访问记录接口
function visitProduct(id,type){
	var data = {
		ID:id,
		ModelID:'4',
		ProductDetail: type==1?"1":'',
		ProductVideo:type==2?"1":'',
		ProductIntroduction:type==3?"1":''
		}
	
	globalData.ajaxPost('/api/Product/VisitProduct', data, function(res) {
		console.log(res)
	})		
}

//vue 过滤器
Vue.filter("add_baseUrl", function(val) {   //全局方法 Vue.filter() 注册一个自定义过滤器,必须放在Vue实例化前面
    var newval = globalData.constParam.url.baseUrl+'/' + val
	return newval
});
Vue.filter("cut_text", function(val,length) {   //全局方法 Vue.filter() 注册一个自定义过滤器,必须放在Vue实例化前面
	var len = Number(length) || 10
	if(val.length<Number(len)){
		return val
	}else{
		var newval = val.substring(0,len)+ "..."
		return newval;
	}
});

Vue.filter("translate_text", function(val,length) {   //全局方法 Vue.filter() 注册一个自定义过滤器,必须放在Vue实例化前面
	var newval = val.replace(/<.+?>/g, "").replace(/&nbsp;/g,"");	
	var len = Number(length) || 10
	if(newval.length<Number(len)){
		return newval
	}else{
		var newval = newval.substring(0,len)+ "..."
		return newval;
	}
});
Vue.filter("translate_time", function(val) {   //全局方法 Vue.filter() 注册一个自定义过滤器,必须放在Vue实例化前面
	if(val){
		var newval = val.replace(/\//g, "-");
		return newval	
	}
	
});